package com.cloud.adrian.novel.resource.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cloud.adrian.novel.common.constant.ErrorCodeEnum;
import com.cloud.adrian.novel.common.constant.SystemConfigConstants;
import com.cloud.adrian.novel.common.resp.RestResp;
import com.cloud.adrian.novel.config.exception.BusinessException;
import com.cloud.adrian.novel.resource.dto.resp.ImgVerifyCodeResp;
import com.cloud.adrian.novel.resource.manager.redis.VerifyCodeManager;
import com.cloud.adrian.novel.resource.service.ResourceService;
import com.cloud.adrian.novel.user.dto.resp.UserRegisterRespDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @Author: xiangguiliang
 * @version: 1.0
 * @since: 2024/05/24
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ResourceServiceImpl implements ResourceService {
    private final VerifyCodeManager verifyCodeManager;
    @Value("${novel.file.upload.path}")
    private String fileUploadPath;

    @Override
    public RestResp<ImgVerifyCodeResp> getImgVerifyCode() throws IOException {
        String sessionId = IdWorker.get32UUID();
        return RestResp.ok(ImgVerifyCodeResp.builder()
                        .sessionId(sessionId)
                        .img(verifyCodeManager.genImgVerifyCode(sessionId))
                        .build());
    }

    @Override
    public RestResp<String> uploadImage(MultipartFile file) throws IOException {
        LocalDateTime now = LocalDateTime.now();
        String filePath = SystemConfigConstants.IMAGE_UPLOAD_DIR
                + now.format(DateTimeFormatter.ofPattern("yyyy")) + File.separator
                + now.format(DateTimeFormatter.ofPattern("MM")) + File.separator
                + now.format(DateTimeFormatter.ofPattern("dd"));
        String oriName = file.getOriginalFilename();
        assert oriName != null;
        String fileName = IdWorker.get32UUID() + oriName.substring(oriName.lastIndexOf("."));
        Path saveFilePath = Paths.get(fileUploadPath, filePath, fileName);
        Path parent = saveFilePath.getParent();
        if (!Files.exists(parent)) {
            try {
                Files.createDirectories(parent);
            } catch (IOException e) {
                throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_ERROR);
            }
        }

        try {
            Files.copy(file.getInputStream(), saveFilePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_ERROR);
        }
        if (Objects.isNull(ImageIO.read(saveFilePath.toFile()))) {
            // 不是图片
            Files.delete(saveFilePath);
            throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_TYPE_NOT_MATCH);
        }
        return RestResp.ok(filePath + File.separator + fileName);
    }
}
